<template>
    <div>
        <el-table border :data='rowsData' class='w-100'>
            <el-table-column align='center' prop='name' label='名称' />
            <el-table-column align='center' prop='code' label='编码' />
            <el-table-column align='center' label='url'>
                <template #default='scope'>
                    <template v-if='scope.row.urls'>
                        {{scope.row.urls.toString()}}
                    </template>
                </template>
            </el-table-column>
            <el-table-column align='center' prop='remark' label='备注' />
            <el-table-column align='center' label='操作'>
                <template #default='scope'>
                    <XRequestButton isConfirm confirmText='确定删除该权限吗' :click='async () => deleteSingleRule(scope.row.id, scope.$index)'>
                        <el-button type='text'>删除</el-button>
                    </XRequestButton>
                    <el-button type='text' @click='openEdit(scope.row)'>编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class='m-t-20'>
            <el-button type='primary' size='mini' @click='dialogVisible = true'>新 增</el-button>
        </div>
    </div>

    <el-dialog v-model='dialogVisible' :title='(formData.id ? "编辑" : "新增")' width='500px' @close='resetForm'>
        <el-form ref='formRef' size='mini' label-width='80px' :rules='rules' :model='formData'>
            <el-form-item label='名称' prop='name'>
                <el-input type='text' clearable show-word-limit :maxlength='rules.name[1].max' v-model='formData.name' />
            </el-form-item>
            <el-form-item label='编码' prop='code'>
                <el-input type='text' clearable show-word-limit :maxlength='rules.code[1].max' v-model='formData.code' />
            </el-form-item>
            <el-form-item label='URL' prop='urls'>
                <el-input type='text' clearable placeholder='多个url可用,分割' v-model='formData.urls' />
            </el-form-item>
            <el-form-item label='请求类型' prop='methods' :rules='[{required : false}]'>
                <el-select class='w-100' size='mini' multiple v-model='formData.methods' placeholder=" ">
                    <el-option value='GET'>GET</el-option>
                    <el-option value='POST'>POST</el-option>
                    <el-option value='PUT'>PUT</el-option>
                    <el-option value='DELETE'>DELETE</el-option>
                </el-select>
            </el-form-item>
            <el-form-item label='备注' prop='remark' :rules='[{required : false}]'>
                <el-input type='text' clearable show-word-limit :maxlength='50' v-model='formData.remark' />
            </el-form-item>
            <div style='display:none'>
                <el-form-item label='id' prop='id' :rules='[{required : false}]'>
                    <el-input type='hidden' v-model.number='formData.id'></el-input>
                </el-form-item>
            </div>
        </el-form>
        <template #footer>
            <el-button size='mini' @click='dialogVisible=false'>取 消</el-button>
            <XRequestButton class='m-l-20' :click='submit'>
                <el-button size='mini' type='primary'>确 定</el-button>
            </XRequestButton>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup>
    import { ElMessage } from "element-plus"
import { nextTick, reactive, ref, watch } from "vue"
    import { getRulesApi, addRuleApi, editRuleApi, deleteRuleApi } from '../../../api/permissionRule'
import { filterEmpty } from "../../../utils"

    const props = defineProps<{
        menuId:number
    }>()

    const rowsData:any[] = reactive([])

    const dialogVisible = ref(false)
    const formRef = ref()
    const formData = reactive({
        id : 0,
        menuId : 0,
        name : '',
        code : '',
        urls : '',
        remark : '',
        methods : []
    })

    

    const rules = reactive<{[key in keyof (typeof formData)]?:any[]}>({
        name : [
            {
                required : true,
                message : '请输入名称'
            },
            {
                min : 1,
                max : 10,
                message: '名称长度在1-10个字符之间',
            }
        ],

        code : [
            {
                required : true,
                message : '请输入编码'
            },
            {
                max : 30,
                message: '编码长度不能超过30个字符',
            }
        ],

        urls : [
            {
                required : true,
                message : '请输入urls'
            }
        ]
    })

    function getRules() {
        getRulesApi(props.menuId).then(rules => {
            rowsData.splice(0)
            rowsData.push(...rules)
        })
    }


    async function submit() {
        try {
            await formRef.value.validate()
            let data = {...JSON.parse(JSON.stringify(formData)), menuId : props.menuId}
            data.urls = data.urls.split(',')
            filterEmpty(data)

            const res = await (data.id ? editRuleApi(data.id, data) : addRuleApi(data))
            if(res.success) {
                ElMessage.success('保存成功')
                resetForm()
                dialogVisible.value = false
                getRules()
            }else {
                ElMessage.error!(res.msg)
            }

        } catch (error) {
            console.log(error)
        }
    }

    function openEdit(scope) {
        dialogVisible.value = true
        nextTick(() => {
            formData.id = scope.id
            formData.name = scope.name
            formData.code = scope.code
            if(scope.urls) {
                formData.urls = scope.urls.join(',')
            }
            
            formData.remark = scope.remark
            if(scope.methods) {
                formData.methods = scope.methods
            }
        })
    }

    async function deleteSingleRule(id:number, index:number) { //删除
        const res = await deleteRules([id])
        if(res.success) {
            ElMessage.success!('删除成功')
            rowsData.splice(index, 1)
        }else {
            ElMessage.error!(res.msg)
        }
    }

    async function deleteRules(ids:number[]) {
        return deleteRuleApi(ids)
    }

    function resetForm() {
        formRef.value.resetFields()
        nextTick(() => {
            formRef.value.clearValidate()
        })
    }


    getRules()

    watch(() => props.menuId, () => {
        getRules()
    })

</script>